package com.pd.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.pd.constant.SysContant;
import com.pd.exception.BusinessException;
import com.pd.exception.SystemException;
import com.pd.domain.ResponseVo;
import com.pd.web.util.UrlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by dong peng on 2018/1/21.
 *
 * 统一处理所有异常
 */
public class CommonExceptionHandler implements HandlerExceptionResolver {

    private Logger log = LoggerFactory.getLogger(CommonExceptionHandler.class);

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        ResponseVo result = new ResponseVo();

        if(BusinessException.class.isAssignableFrom(ex.getClass())) {
            BusinessException bex = (BusinessException) ex;
            result.setTip(SysContant.BIZ_EXCEPTION);
            result.setDesc(bex.getMessage());
        }else if(SystemException.class.isAssignableFrom(ex.getClass())) {
            SystemException sysEx = (SystemException) ex;
            result.setTip(SysContant.SYS_EXCEPTION);
            result.setDesc(sysEx.getMessage());
            log.error("系统异常",ex);
        } else {
            // 系统错误
            result.setTip(SysContant.SYS_ERROR);
            result.setDesc("系统错误,请联系管理员");
            log.error("系统错误",ex);
            log.error("CommonExceptionHandler catche the System Error, ", ex);
        }

        if(UrlUtil.isAjax(request)) {
            response.setContentType("application/json;charset=UTF-8");
            try {
                response.getWriter().println(JSON.toJSONString(result));
            } catch (IOException e) {
                log.error("返回处理异常",e);
            }
        }else {
            response.setContentType("text/html;charset=UTF-8");
            request.setAttribute("code", result.getCode());
            request.setAttribute("description", result.getDesc());
            return new ModelAndView("error/error.html");
        }

        return new ModelAndView();
    }
}
